import base64
import os
import sys

# 将项目根目录添加到Python模块搜索路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from utils.logger_config import logger


def audio_to_base64(file_path):
    """将音频文件转换为base64编码"""
    try:
        with open(file_path, "rb") as audio_file:
            encoded_string = base64.b64encode(audio_file.read())
            return encoded_string.decode("utf-8")
    except Exception as e:
        logger.error(f"转换失败: {str(e)}")
        return None


if __name__ == "__main__":
    if len(sys.argv) != 2:
        logger.error(
            "用法: python audio_to_base64.py <音频文件路径>"
        )
        sys.exit(1)

    file_path = sys.argv[1]
    base64_string = audio_to_base64(file_path)

    if base64_string:
        logger.info(f"Base64编码 (长度: {len(base64_string)}):")
        logger.info(base64_string[:100] + "...")  # 只打印前100个字符

        # 将完整编码保存到文件
        output_file = file_path + ".b64"
        with open(output_file, "w") as f:
            f.write(base64_string)
        logger.info(f"完整编码已保存到: {output_file}")
